package com.woniuxy.mycollection;

/**
 * description: SxtArrayList <br>
 * date: 2022/2/2 11:40 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

/**
 * 实现ArrayList
 * 加扩容
 *
 * @param <E>
 */
public class SxtArrayList02<E> {
    private Object[] elementData;
    private int size;

    private static final int DEFALT_CAPACITY = 10;

    public SxtArrayList02() {
        elementData = new Object[DEFALT_CAPACITY];
    }

    public SxtArrayList02(int capacity) {
        if (capacity < 0) {
            throw new RuntimeException("容器的容量不能为负数");
        } else if (capacity == 0) {
            elementData = new Object[DEFALT_CAPACITY];
        } else {
            elementData = new Object[capacity];
        }

    }

    public void add(E element) {
        if (size == elementData.length) {
            //10-->10+10/2=15
            Object[] newArray = new Object[elementData.length + (elementData.length >> 1)];
            System.arraycopy(elementData, 0, newArray, 0, elementData.length);
            elementData = newArray;
        }
        elementData[size++] = element;
    }

    public E get(int index) {
        checkRange(index);
        return (E) elementData[index];
    }

    public void set(E element, int index) {
        checkRange(index);
        elementData[index] = element;
    }

    public void checkRange(int index) {
        //索引合法判断[0,size] 10  0-9
        if (index < 0 || index > size - 1) {
            //不合法
            throw new RuntimeException("索引不合法！" + index);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < size; i++) {
            sb.append(elementData[i] + ",");
        }
        sb.setCharAt(sb.length() - 1, ']');
        return sb.toString();
    }

    public static void main(String[] args) {
        SxtArrayList02 s1 = new SxtArrayList02();
        for (int i = 0; i < 20; i++) {
            s1.add("ff" + i);
        }
        System.out.println(s1);
        System.out.println(s1.size);
        System.out.println(s1.get(10));
        s1.set("方法", 1);
        System.out.println(s1);
        System.out.println(s1.get(1));
        s1.set("驻足", 3);
        System.out.println(s1);
        System.out.println(s1.get(11));
    }
}
